"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.hideInstance = exports.WebLayout = void 0;

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _configContext = require("../../../extends/configContext");

var _pcController = _interopRequireDefault(require("./web-components/pc-controller"));

var _previewerController = _interopRequireDefault(require("./web-components/previewer-controller"));

var _previewer = _interopRequireDefault(require("./web-components/previewer"));

var _miniController = _interopRequireDefault(require("./web-components/mini-controller"));

var _isMobile = _interopRequireDefault(require("../../../utils/is-mobile"));

var _reactDom = _interopRequireDefault(require("react-dom"));

var _eventemitter = _interopRequireDefault(require("eventemitter3"));

var _report = require("../../../utils/report");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var PreviewerEmitter = /*#__PURE__*/function (_EventEmitter) {
  _inherits(PreviewerEmitter, _EventEmitter);

  var _super = _createSuper(PreviewerEmitter);

  function PreviewerEmitter() {
    _classCallCheck(this, PreviewerEmitter);

    return _super.apply(this, arguments);
  }

  return PreviewerEmitter;
}(_eventemitter.default);

var previewerEmitter = new PreviewerEmitter();
/**
 * ModalHelper helpers resolve the modal scrolling issue on mobile devices
 * https://github.com/twbs/bootstrap/issues/15852
 * requires document.scrollingElement polyfill https://github.com/yangg/scrolling-element
 */

var ModalHelper = function (bodyCls) {
  var scrollTop;
  return {
    afterOpen: function afterOpen() {
      scrollTop = document.scrollingElement.scrollTop;
      document.body.classList.add(bodyCls);
      document.body.style.top = "".concat(-scrollTop, "px");
    },
    beforeClose: function beforeClose() {
      document.body.classList.remove(bodyCls); // scrollTop lost after set position:fixed, restore it back.

      document.scrollingElement.scrollTop = scrollTop;
    }
  };
}('modal-open');

var WebLayout = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
  var _ref$imgs = _ref.imgs,
      imgs = _ref$imgs === void 0 ? [] : _ref$imgs,
      _ref$currentUrl = _ref.currentUrl,
      currentUrl = _ref$currentUrl === void 0 ? '' : _ref$currentUrl,
      visible = _ref.visible,
      _ref$onClose = _ref.onClose,
      onClose = _ref$onClose === void 0 ? function () {} : _ref$onClose,
      _ref$onError = _ref.onError,
      onError = _ref$onError === void 0 ? function () {
    return '';
  } : _ref$onError;
  (0, _report.useReport)({
    componentName: 'imagePreviewer'
  });

  var viewerDomRef = _react.default.useRef(null);

  var _useConfig = (0, _configContext.useConfig)(),
      clsPrefix = _useConfig.clsPrefix;

  var _React$useState = _react.default.useState(0),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      currShowImgIdx = _React$useState2[0],
      setCurrShowImgIdx = _React$useState2[1];

  var _React$useState3 = _react.default.useState(false),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      innerVisible = _React$useState4[0],
      setInnerVisible = _React$useState4[1]; // 控制显示隐藏的动画


  var _React$useState5 = _react.default.useState(false),
      _React$useState6 = _slicedToArray(_React$useState5, 2),
      previewerVisible = _React$useState6[0],
      setPreviewerVisible = _React$useState6[1];

  var showAnimTimerRef = _react.default.useRef(null);

  var openFlag = _react.default.useRef(false);

  var clickLockFlag = _react.default.useRef(false);

  _react.default.useEffect(function () {
    var hide = function hide() {
      setInnerVisible(false);
    };

    var show = function show() {
      setInnerVisible(true);
    };

    previewerEmitter.on('hide', hide);
    previewerEmitter.on('show', show);
    return function () {
      previewerEmitter.removeListener('hide', hide);
      previewerEmitter.removeListener('show', show);
    };
  }, []);

  _react.default.useEffect(function () {
    if (innerVisible) {
      showAnimTimerRef.current = setTimeout(function () {
        setPreviewerVisible(true);
      }, 100);
    } else {
      showAnimTimerRef.current = setTimeout(function () {
        setPreviewerVisible(false);
      }, 100);
    }

    return function () {
      clearTimeout(showAnimTimerRef.current);
    };
  }, [innerVisible]);

  _react.default.useEffect(function () {
    if (visible) {
      openFlag.current = true;
      ModalHelper.afterOpen();
    } else {
      if (openFlag.current) {
        openFlag.current = false;
        ModalHelper.beforeClose();
      }
    }
  }, [innerVisible]);

  _react.default.useEffect(function () {
    var onTouchMove = function onTouchMove(e) {
      if (typeof e.cancelable !== 'boolean' || e.cancelable) {
        e.preventDefault();
      }
    };

    var onTouchEnd = function onTouchEnd(e) {
      if (typeof e.cancelable !== 'boolean' || e.cancelable) {
        e.preventDefault();
      }
    };

    if (typeof window !== 'undefined' && innerVisible) {
      document.addEventListener('touchmove', onTouchMove, {
        passive: false
      });
      document.addEventListener('toouchend', onTouchEnd, {
        passive: false
      });
    }

    return function () {
      if (typeof window !== 'undefined') {
        document.removeEventListener('touchmove', onTouchMove);
        document.removeEventListener('toouchend', onTouchEnd);
      }
    };
  }, [innerVisible]);

  var show = (0, _react.useCallback)(function () {
    setInnerVisible(true);
  }, [imgs, onClose]);
  var hide = (0, _react.useCallback)(function () {
    setInnerVisible(false);
  }, []);
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      show: show,
      hide: hide
    };
  }, [show, hide]);
  (0, _react.useEffect)(function () {
    setInnerVisible(visible);
  }, [visible]);
  (0, _react.useEffect)(function () {
    var currentIndex = imgs.indexOf(currentUrl);
    if (currentIndex === -1) currentIndex = 0;
    setCurrShowImgIdx(currentIndex);
  }, [currentUrl, imgs]); // 暂不支持 ssr

  if (typeof window === 'undefined') {
    return null;
  }

  var IS_MOBILE = false;

  if (typeof window !== 'undefined') {
    IS_MOBILE = (0, _isMobile.default)();
  }

  var onCloseImpl = function onCloseImpl() {
    setPreviewerVisible(false);
    setTimeout(function () {
      setInnerVisible(false);
      onClose();
    }, 300);
  };

  return /*#__PURE__*/_reactDom.default.createPortal(innerVisible && /*#__PURE__*/_react.default.createElement("div", {
    ref: viewerDomRef,
    onClick: function onClick(e) {
      e.stopPropagation();
      e.preventDefault();

      if (!IS_MOBILE) {
        if (!clickLockFlag.current) {
          setInnerVisible(false);
          onClose();
        }
      }
    },
    className: (0, _classnames.default)("".concat(clsPrefix, "-img-previewer"), {
      'is-mobile': IS_MOBILE,
      'is-active': previewerVisible
    })
  }, /*#__PURE__*/_react.default.createElement(_miniController.default, {
    imgUrls: imgs,
    currentImgIdx: currShowImgIdx
  }), /*#__PURE__*/_react.default.createElement(_pcController.default, {
    imgUrls: imgs,
    currentImgIdx: currShowImgIdx,
    onSwipLeft: function onSwipLeft() {
      setCurrShowImgIdx(function (idx) {
        if (idx < imgs.length - 1) {
          return idx + 1;
        }

        return idx;
      });
    },
    onSwipRight: function onSwipRight() {
      setCurrShowImgIdx(function (idx) {
        if (idx > 0) {
          return idx - 1;
        }

        return idx;
      });
    },
    onClose: onCloseImpl
  }), /*#__PURE__*/_react.default.createElement(_previewer.default, {
    imgUrls: imgs,
    currentImgIdx: currShowImgIdx,
    onSwipLeft: function onSwipLeft() {
      setCurrShowImgIdx(function (idx) {
        if (idx < imgs.length - 1) {
          return idx + 1;
        }

        return idx;
      });
    },
    onSwipRight: function onSwipRight() {
      setCurrShowImgIdx(function (idx) {
        if (idx > 0) {
          return idx - 1;
        }

        return idx;
      });
    },
    onError: onError,
    onClose: onCloseImpl,
    onClickLock: function onClickLock() {
      clickLockFlag.current = true;
    },
    onClickUnLock: function onClickUnLock() {
      clickLockFlag.current = false;
    }
  }), /*#__PURE__*/_react.default.createElement(_previewerController.default, {
    imgUrls: imgs,
    onError: onError,
    currentImgIdx: currShowImgIdx,
    onImgClick: function onImgClick(index) {
      setCurrShowImgIdx(index);
    }
  })), document.getElementsByTagName('body')[0]);
}); // 隐藏 viewer 实例

exports.WebLayout = WebLayout;

var hideInstance = function hideInstance() {
  previewerEmitter.emit('hide');
};

exports.hideInstance = hideInstance;